package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.TheContactAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.TheContact;
import com.zmx.patientend.pojo.User;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/12/6  14:36
 * 功 能：联系人
 */
public class TheContactActivity extends BaseActivity {

    @BindView(R.id.reView)
    RecyclerView reView;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.no_data)
    TextView no_data;
    private String patient_id;

    private TheContactAdapter adapter;
    private List<TheContact> lists;
    private List<User> users;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_the_contact;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        patient_id = this.getIntent().getStringExtra("patient_id");
        adapter = new TheContactAdapter(mActivity);
        reView.setLayoutManager(new LinearLayoutManager(mActivity));
        reView.setAdapter(adapter);
        lists = new ArrayList<>();
        users = new ArrayList<>();

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {
                alert_label(listPosition);
            }
        });

        getFamilyNumber();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        lists.clear();
                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1){

                            JSONArray data = object.getJSONArray("data");
                            Gson gson = new Gson();
                            for (int i = 0; i < data.length(); i++) {

                                TheContact tc = gson.fromJson(data.getJSONObject(i).toString(), TheContact.class);
                                lists.add(tc);

                                User user = new User();
                                user.setMobileNo(tc.getMobileNo());
                                user.setName(tc.getName());
                                users.add(user);

                            }
                            adapter.setListAndNotifyDataSetChanged(lists);

                            if (lists.size()>0){

                                no_data.setVisibility(View.GONE);

                            }else{

                                no_data.setVisibility(View.VISIBLE);

                            }

                        }else{
                            Toast(object.getString("msg"));
                            no_data.setVisibility(View.VISIBLE);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                        if (object.getInt("code") == 1){
                            getFamilyNumber();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };


    public void getFamilyNumber() {

        List<String> ls = new ArrayList<>();
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getFamilyNumber");
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi", params, handler, 1, 404);

    }

    /**
     *  * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *  *
     *  * @param phoneNum 电话号码
     *  
     */
    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.button)
    public void onViewClicked() {

        alert_label();

    }


    public void alert_label(){

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);

        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_sos, null);//这里必须是final的
        final EditText et = view.findViewById(R.id.editText);
        final EditText name = view.findViewById(R.id.name);
        et.setInputType(InputType.TYPE_CLASS_NUMBER);
        builder.setTitle("填写信息");

        final AlertDialog dialog = builder.create();
        dialog.setView(view);

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

            }
        });
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(et.getText().toString()) && !TextUtils.isEmpty(name.getText().toString())) {

                    User user = new User();
                    user.setName(name.getText().toString());
                    user.setMobileNo(et.getText().toString());
                    users.add(user);
                    Gson gson = new Gson();
                    String taskInfo = gson.toJson(users);

                    setFamilyNumber(taskInfo);
                    dialog.dismiss();

                } else {

                    Toast("非法输入!");

                }


            }
        });


    }


    public void alert_label(Integer listPos){

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        User user = users.get(listPos);
        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_sos, null);//这里必须是final的
        final EditText et = view.findViewById(R.id.editText);
        et.setText(user.getMobileNo());
        final EditText name = view.findViewById(R.id.name);
        name.setText(user.getName());
        et.setInputType(InputType.TYPE_CLASS_NUMBER);
        builder.setTitle("填写信息");

        final AlertDialog dialog = builder.create();
        dialog.setView(view);

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

            }
        });
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(et.getText().toString()) && !TextUtils.isEmpty(name.getText().toString())) {

                    user.setName(name.getText().toString());
                    user.setMobileNo(et.getText().toString());
                    users.set(listPos,user);
                    Gson gson = new Gson();
                    String taskInfo = gson.toJson(users);

                    setFamilyNumber(taskInfo);
                    dialog.dismiss();

                } else {

                    Toast("非法输入!");

                }


            }
        });


    }


    public void setFamilyNumber(String user) {

        List<String> ls = new ArrayList<>();
        ls.add(user);
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "setFamilyNumber");
        params.put("data[patient_id]", patient_id);
        params.put("data[familyNumbers]", user);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi", params, handler, 2, 404);

    }

}
